#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>

#define FIFO_FILE "/tmp/my_fifo"
#define MAX_BUFFER_SIZE 256

int main() {
    int fd;
    char buffer[MAX_BUFFER_SIZE];
    int ret;

    // 检查FIFO文件是否存在
    if (access(FIFO_FILE, F_OK) == -1) {
        printf("Reader: FIFO file does not exist. Waiting for writer to create it...\n");
        // 可以在这里创建FIFO，但通常由写进程创建
        // mkfifo(FIFO_FILE, 0666);
    }

    printf("Reader: Opening FIFO for reading...\n");

    // 打开管道进行读操作
    fd = open(FIFO_FILE, O_RDONLY);
    if (fd < 0) {
        perror("open FIFO failed");
        exit(EXIT_FAILURE);
    }

    printf("Reader: FIFO opened successfully\n");
    printf("Reader: Waiting for messages...\n");

    // 循环从管道读取数据
    while (1) {
        // 读取数据
        ret = read(fd, buffer, MAX_BUFFER_SIZE);
        if (ret < 0) {
            perror("read failed");
            close(fd);
            exit(EXIT_FAILURE);
        } else if (ret == 0) {
            // 如果返回0，说明写端关闭了管道
            printf("Reader: Writer closed the pipe\n");
            break;
        }
        
        printf("Reader: Received message: %s\n", buffer);
        
        // 如果收到exit消息，则退出循环
        if (strcmp(buffer, "exit") == 0) {
            printf("Reader: Received exit command\n");
            break;
        }
    }

    // 关闭文件描述符
    close(fd);
    
    // 可选：删除FIFO文件
    // unlink(FIFO_FILE);
    
    printf("Reader: Program terminated\n");
    return 0;
}